<template>
  <div>
    <Category :scene="scene"></Category>
    <el-card style="margin: 10px 0">
      <!-- 展示已有属性 -->
      <div v-show="scene == 0">
        <!-- 添加属性按钮 -->
        <el-button type="primary" icon="Plus" :disabled="!categoryStore.c3Id" @click="addAttr">添加属性</el-button>
        <el-table border style="margin: 15px 0px" align="center" :data="attrArr">
          <!-- 序号 -->
          <el-table-column label="序号" type="index" align="center" width="100px"></el-table-column>
          <!-- 属性名称 -->
          <el-table-column label="属性名称" align="center" width="150px" prop="attrName"></el-table-column>
          <el-table-column label="属性值名称">
            <template #default="{ row }">
              <el-tag style="margin: 5px" v-for="item in row.attrValueList" :key="item.id">{{ item.valueName }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200px" align="center">
            <template #default="{ row }">
              <el-button type="primary" icon="Edit" @click="updateAttr(row)"></el-button>
              <el-popconfirm :title="`你确定要删除${row.attrName}吗?`" @confirm="deleteAttr(row.id)">
                <template #reference>
                  <el-button type="danger" icon="Delete"></el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 添加或修改已有属性 -->
      <div v-show="scene == 1">
        <!-- 添加属性名称输入框 -->
        <el-form :inline="true">
          <el-form-item label="属性名称">
            <el-input placeholder="请输入属性名称" v-model="attrParams.attrName"></el-input>
          </el-form-item>
        </el-form>
        <!-- 添加属性值按钮 -->
        <el-button :disabled="!attrParams.attrName" type="primary" icon="Plus" @click="addAttrValue">添加属性值</el-button>
        <!-- 取消按钮 -->
        <el-button @click="cancel">取消</el-button>
        <el-table border style="margin: 20px auto" :data="attrParams.attrValueList">
          <!-- 序号 -->
          <el-table-column width="100px" type="index" align="center" label="序号"></el-table-column>
          <!-- 属性值 -->
          <el-table-column label="属性值">
            <template #default="{ row, $index }">
              <el-input :ref="(vc: any) => (inputArr[$index] = vc)" v-show="row.flag" placeholder="请输入属性值名称"
                v-model="row.valueName" @blur="toLook(row, $index)"></el-input>
              <div v-show="!row.flag" @click="toEdit(row, $index)">
                {{ row.valueName }}
              </div>
            </template>
          </el-table-column>
          <!-- 操作 -->
          <el-table-column label="操作">
            <template #default="{ row, $index }">
              <el-button type="danger" icon="Delete" @click="($event: any) => attrParams.attrValueList.splice($index, 1)
                "></el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 保存按钮 -->
        <el-button :disabled="!attrParams.attrName || attrParams.attrValueList.length === 0
          " type="primary" @click="save">保存</el-button>
        <!-- 取消按钮 -->
        <el-button @click="cancel">取消</el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { nextTick, onBeforeUnmount, reactive, ref, toRaw, watch } from "vue";
import { reqAttr, reqAddOrUpdateAttr, reqDleteAttr } from "@/api/product/attr";
import useCategoryStore from "@/store/modules/category";
import { Attr, AttrValue } from "@/api/product/attr/type";
import { ElMessage } from "element-plus";

//#region 数据相关定义
let categoryStore = useCategoryStore();
// 已有属性数组
let attrArr = ref<Attr[]>([]);
// 场景控制
let scene = ref<number>(0);
// 获取新增属性的input元素
let inputArr = ref<any>([]);
// 新增的属性
let attrParams = reactive<Attr>({
  attrName: "",
  attrValueList: [],
  categoryId: "",
  categoryLevel: 3,
});
//#endregionndregion

//监听仓库三级Id的变化
watch(
  () => categoryStore.c3Id,
  () => {
    attrArr.value = [];
    if (!categoryStore.c3Id) return;
    getAttr();
  }
);

// 获取已有的属性与属性值方法
const getAttr = async () => {
  const { c1Id, c2Id, c3Id } = categoryStore;
  let result = await reqAttr(c1Id, c2Id, c3Id);
  if (result.code == 200) {
    attrArr.value = result.data;
  }
};

// 添加属性按钮
const addAttr = () => {
  Object.assign(attrParams, {
    attrName: "",
    attrValueList: [],
    categoryId: categoryStore.c3Id,
    categoryLevel: 3,
  });
  scene.value = 1;
};

// 修改属性按钮
const updateAttr = (row: Attr) => {
  scene.value = 1;
  Object.assign(attrParams, structuredClone(toRaw(row)));
};

// 取消按钮
const cancel = () => {
  scene.value = 0;
};

// 添加属性值按钮的回调
const addAttrValue = () => {
  attrParams.attrValueList.push({
    valueName: "",
    flag: true,
  });
  nextTick(() => {
    inputArr.value[attrParams.attrValueList.length - 1].focus();
  });
};

// 保存按钮
const save = async () => {
  let result: any = await reqAddOrUpdateAttr(attrParams);
  if (result.code == 200) {
    scene.value = 0;
    ElMessage({
      type: "success",
      message: attrParams.id ? "修改成功" : "添加成功",
    });
    getAttr();
  } else {
    ElMessage({
      type: "error",
      message: attrParams.id ? "修改失败" : "添加失败",
    });
  }
};

// 表单元素失去焦点事件回调
const toLook = (row: AttrValue, $index: number) => {
  let repeat = attrParams.attrValueList.find((item: AttrValue) => {
    if (item != row) {
      return item.valueName === row.valueName;
    }
  });
  if (repeat) {
    ElMessage({
      type: "error",
      message: "属性值不能重复",
    });
    attrParams.attrValueList.splice($index, 1);
    return;
  }
  if (!row.valueName.trim()) {
    ElMessage({
      type: "error",
      message: "属性值不能为空",
    });
    attrParams.attrValueList.splice($index, 1);
    return;
  }
  row.flag = false;
};

// div点击事件
const toEdit = (row: AttrValue, $index: number) => {
  row.flag = true;
  nextTick(() => {
    inputArr.value[$index].focus();
  });
};

// 删除属性按钮回调
const deleteAttr = async (attrId: number) => {
  let result: any = await reqDleteAttr(attrId);
  if (result.code == 200) {
    ElMessage({
      type: "success",
      message: "删除成功",
    });
    getAttr();
  } else {
    ElMessage({
      type: "error",
      message: "删除失败",
    });
  }
};

onBeforeUnmount(() => {
  categoryStore.$reset();
});
</script>

<style scoped></style>